package com.searchengine.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.util.Version;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.base.action.BaseAction;
import com.searchengine.core.SearchObject;
import com.searchengine.entity.ContentObject;
import com.searchengine.service.ContentService;
import com.searchengine.util.PackContentObject;
/**
 *  Class Name: SearchAction.java   搜索类
 *  @author JLC From liutime.com
 *  @version 1.0
 */
@Controller
@Scope("prototype")
public class SearchAction extends BaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3141706082945311957L;
	/**
	 * 文章内容服务接口
	 */
	private ContentService contentService;
	/**
	 * 搜索关键字
	 */
	private String keyWord;
	/**
	 * 结果集
	 */
	private List<ContentObject> searcheResult;
	/**
	 * 内容对象
	 */
	private ContentObject contentObj;
	
	/**
	 *  Function:
	 *  @author  
	 *  @return
	 *  @throws Exception
	 */
	@Action(
	  value = "index", 
	  results = { @Result(name = SUCCESS,  location = "/result.jsp") }
	)  
	public String searcheContent() throws Exception {  
        searcheResult =  new ArrayList<ContentObject>();
        try{
        	//当查询条件不存在时，查询数据库
        	if(StringUtils.isEmpty(keyWord)){
        		searcheResult = contentService.getContentList();
        		return SUCCESS;
        	}
            Version v = Version.LUCENE_43;
            //取得查询对象
            IndexReader[] readers =  SearchObject.getInstance().getSearcherReads();
            MultiReader mReaders = new MultiReader(readers);
            IndexSearcher indexSearch = new  IndexSearcher(mReaders);
            Analyzer analyzer =new StandardAnalyzer(v);
            //创建boolean查询
            BooleanQuery query = new BooleanQuery();
            String[] field = { "title", "content"};
            BooleanClause.Occur[] flags = new BooleanClause.Occur[2];
            flags[0] = BooleanClause.Occur.SHOULD;
            flags[1] = BooleanClause.Occur.SHOULD;
            Query query1 = MultiFieldQueryParser.parse(v, QueryParser.escape(keyWord), field, flags, analyzer);
            //query.add(query1, Occur.MUST);
            
            //日期范围查询
            Calendar calendar = Calendar.getInstance();
            //查询两个月以内的数据
			calendar.add(Calendar.DAY_OF_MONTH, -60);
			Date lastMonth = calendar.getTime();
			query.add(NumericRangeQuery.newLongRange("createDate", lastMonth.getTime(), new Date().getTime(), true, true), Occur.MUST);
            //根据ID范围查询
			//query.add(NumericRangeQuery.newIntRange("id", 0, 20, true, true), Occur.MUST);
			//true为降序，false为升序
			SortField field1 = new SortField("createDate", SortField.Type.LONG,false); 
			Sort sort = new Sort(field1);
			//取得查询结果
			TopDocs topDocs =   indexSearch.search(query,100000, sort);  
			
            //TopScoreDocCollector topCollector = TopScoreDocCollector.create(10000, true,sort);
           // indexSearch.search(query, topCollector); 
           // TopDocs topDocs = topCollector.topDocs(); 
            int resultCount=topDocs.totalHits;
            for(int i=0;i<resultCount;i++){
                Document doc = indexSearch.doc(topDocs.scoreDocs[i].doc);
                //转换Document对象为内容对象
                //ContentObject content = PackContentObject.convertDocToContent(doc);
                ContentObject content = PackContentObject.convertDocToContent(doc, query1, analyzer);
                //加入到结果列表 返回给前台页面获取
                searcheResult.add(content);
            }
        }catch(Exception e){
            e.printStackTrace();
        }

       return SUCCESS;  
    } 
	
	@Action(
		value = "add", 
		results = { @Result(name = SUCCESS, type="redirect", location = "/index.jsp") }
	)  
	public String addContent() throws Exception {  
		try{
			 
			contentService.saveArticle(contentObj);
		}catch(Exception e){
			e.printStackTrace();
		}
       return SUCCESS;  
	} 
	
	public String getKeyWord() {
		return keyWord;
	}
	public void setKeyWord(String keyWord) {
		this.keyWord = keyWord;
	}
	public List<ContentObject> getSearcheResult() {
		return searcheResult;
	}
	public ContentObject getContentObj() {
		return contentObj;
	}
	public void setContentObj(ContentObject contentObj) {
		this.contentObj = contentObj;
	}
	public void setContentService(ContentService contentService) {
		this.contentService = contentService;
	}
}
